package filter;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(filterName = "AdminFilter", urlPatterns = "/admin/*", initParams = {
        @WebInitParam(name = "username", value = "root"),
        @WebInitParam(name="url",value="url")
})
public class AdminFilter implements Filter {

    public AdminFilter() {
        System.out.println("constructor");
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        System.out.println("init");
        System.out.println("filter-name: " + config.getFilterName());
        System.out.println("username: " + config.getInitParameter("username"));
        System.out.println("url: " + config.getInitParameter("url"));
        System.out.println(config.getServletContext());
    }

    @Override
    public void destroy() {
        System.out.println("destroy");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        System.out.println("doFilter");
        HttpServletRequest request1 = (HttpServletRequest) request;
        Object user = (Object) request1.getSession().getAttribute("user");
        if (user == null) {
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return;
        } else {
            // 继续往下访问
            chain.doFilter(request, response);
        }
    }
}
